<?php

switch($_GET['act'])
{
	case 'orders':
		Orders();
		$title_page = HISTORY_TRANSACTION;
		$tpl = "history_orders";
		break;
		
	case 'orderdetail':
		OrderDetail();
		$title_page = ODER_DETAIL;
		$tpl = "order_detail";
		break;
	
	case 'modify':
		Modify();
		$title_page = MEMBER_DETAIL;
		$tpl = "detail";
		break;
	
	case 'detail':
		Detail();
		$title_page = MEMBER_DETAIL;
		$tpl = "detail";
		break;
	
	case 'comment':
		Comment();
		break;
	
	case 'reg': 
		$tpl = 'reg';
		break;
	
	case 'changepassword':
		$title_page = CHANGE_PASSWORD_TITLE;
		$tpl = 'changepassword';
		break;
		
	case 'changepasssm':		
		$tbChangePassword = "member";
		ChangePass($tbChangePassword);		
		break;
	
	case 'forgotpassword':
		$title_page = LABEL_RESET_PASSWORD;
		$tpl = "forgotpassword";
		break;
	
	case 'resetpassword':
		$tbResetPassword = 'member';
		ForgotPass($tbResetPassword);
		break;
	
	case 'resetpass':
		$tbResetPassword = 'member';
		ResetPass();
		break;

	case 'register':
		$tpl = 'register';
		$title_page = REGISTER_MEMBER;
		break;
		
	case 'regis':
		$tbRegister = "member";
		Register($tbRegister);
		break;
		
	case 'login':
		//Login();		
		$tpl = 'login';
		$title_page = SIGN_IN;
		break;
		
	case 'loginsm':
		Login();		
		$tpl = 'finish';
		break;
		
	case 'logout':
		Logout();
		$tpl = 'finish';
		break;
		
	case 'option':
		Option();
		$tpl = 'option';
		break;	
	
	case 'upload':
		Upload();
		$tpl = 'upload';
		break;	
	case 'uploadsm':
		UploadSM();
		//$tpl = 'upload';
		break;			
						
	case 'send':
		SendMail();
		$tpl = 'finish';
		break;
		
	case 'add_to_fav':
		AddToFav();
		break;
	case 'del_to_fav':
		DelToFav();
		break;
		
	case 'vote':
		Vote();
		break;
		
	case 'optin':
		Optin();
		break;
			
	default:		
		break;
}
function Upload()
{
	global $db,$act, $msg, $FullUrl, $prefix_url, $member;

	$id = $_SESSION['member_id'];
	$sql = "select * from member where id='" . $id . "'";
	$member = $db->getRow($sql);
}
function UploadSM()
{
	global $db,$act, $msg, $FullUrl, $prefix_url, $member;

	$arr['file_1'] = '';
	$arr['file_2'] = '';
	
	if(isset($_FILES['file_1']['name'] ) && $_FILES['file_1']['size']>0){
		$file = $_FILES['file_1']['name'];
		$start = strpos($file,".");
		$type = substr($file,$start,strlen($file));
		//CheckUpload($type);
		$filename = substr($file,0, $start);
		$filename = strtolower($filename);
		
		$filename = $filename . '-' . time() . $type;
		
		copy($_FILES['file_1']['tmp_name'], "./upload/files/" . $filename) ;
		$arr['file_1'] = "upload/files/" . $filename;
	}
	
	if(isset($_FILES['file_2']['name'] ) && $_FILES['file_2']['size']>0){
		$file = $_FILES['file_2']['name'];
		$start = strpos($file,".");
		$type = substr($file,$start,strlen($file));
		//CheckUpload($type);
		$filename = substr($file,0, $start);
		$filename = strtolower($filename);
		
		$filename = $filename . '-' . time() . $type;
		
		copy($_FILES['file_2']['tmp_name'], "./upload/files/" . $filename) ;
		$arr['file_2'] = "upload/files/" . $filename;
	}
	
	if($arr['file_1'] != '' || $arr['file_2'] != '')
	{
		$msg = "Đã upload thành công";
	}
	else
	{
		$msg = "Upload không thành công";
	}
	
	$_SESSION['mess'] = $msg;
	$page=$FullUrl;
	
	page_transfer2($page);	
}

function Option()
{
	global $db,$act, $msg, $FullUrl, $prefix_url, $member;

	$id = $_SESSION['member_id'];
	$sql = "select * from member where id='" . $id . "'";
	$member = $db->getRow($sql);
}

function Optin(){
	global $db, $FullUrl;
	$name = SafeFormValue('name');
	$email = SafeFormValue('email');
	$optin_type = SafeFormValue('optin_type_id');
	
	if(!empty($name) && IsValidEmail($email) && is_numeric($optin_type)){
		$sql = "select otn_type_file from optin_type where otn_type_id = " .$optin_type;
		$r = $db->getRow($sql);
		
		$arr = array();
		$arr['otn_name'] = $name;
		$arr['otn_email'] = $email;
		$arr['otn_otn_type_id'] = $optin_type;
		
		vaInsert('optin',$arr);
		
		$link = 'http://www.' . GetFullDomain() . $FullUrl . "/" . $r['otn_type_file'];
		
		//send email
		include("./includes/mail_config.php");
		global $mail;
		$fh = fopen('./EmailTemplate/OptIn_'.$_SESSION['lg'].'.html', 'r');
			
		$template = fread($fh, filesize('./EmailTemplate/OptIn_'.$_SESSION['lg'].'.html'));
		
		if($r && file_exists($r['otn_type_file']))
		{
			$content = '<a href="' . $link . '" target="_blank">>>Click to download<<</a>';
		}else
			$content = '';
		
		fclose($fh);
		
		$template = str_replace('[CONTENT]', $content, $template);
		$template = str_replace('[NAME]', $name, $template);
		
		$mail_subject = EMAIL_REGISTRATION_CONFIRM_SUBJECT;
		$mail_content = $template;
		$mail_to = $email;
		
		$mail->Subject = $mail_subject;
	
		$mail->MsgHTML($mail_content);
	
		$mail->AddAddress($mail_to, "Webmaster");
		
		if(!$mail->Send()) {
		} else {
			$_SESSION['mess'] = SEND_EMAIL_OPT_IN_SUCCESSFULLY_MESS;
		}
		
		page_transfer2($FullUrl . '/index.php');
	}
}

function OrderDetail()
{
	global $db, $order_detail, $FullUrl, $prefix_url;	
	global $page, $plpage, $set_per_page, $c, $title_bar;
	
	$o_id = isset($_GET['oid'])?$_GET['oid']:'';
	
	if(is_numeric($o_id))
	{
		$sql = "select o.odr_shipping_name, o.odr_shipping_phone, o.odr_shipping_address, 
				o.odr_shipping_email, o.odr_shipping_company, o.odr_payment_name, o.odr_payment_phone, 									                o.odr_payment_address, o.odr_payment_email, o.odr_payment_company ,p.name_vn, p.name_en, p.price,                od.od_pro_quantity from orders o, order_detail od, products p 
				where o.odr_id = od.od_odr_id and od.od_pro_id = p.id and o.odr_id = " . $o_id;
		
		$set_per_page= 100;
		$c = $db->numRows($db->query($sql));
		$plpage = plpage($sql,$page,$set_per_page);
		$sqlstmt = sqlmod($sql,$page,$set_per_page);
		$order_detail = $db->getAll($sqlstmt);
	}
}

function Orders()
{
	global $db, $orders, $FullUrl, $prefix_url;
	global $page, $plpage, $set_per_page, $c, $title_bar;
	if(isset($_SESSION['member_id']))
	{
		$sql = "select odr_id, odr_insert_date, odr_status from orders where odr_mem_id = " . $_SESSION['member_id'];
		
		$set_per_page= 100;
		$c = $db->numRows($db->query($sql));
		$plpage = plpage($sql,$page,$set_per_page);
		$sqlstmt = sqlmod($sql,$page,$set_per_page);
		$orders = $db->getAll($sqlstmt);
	}
}

function Modify()
{
	global $db, $mem_detail, $FullUrl, $prefix_url;
	
	if(isset($_SESSION['member_id']))
	{
		if(CorrectGoogleCaptcha())
		{
			$email = $_POST["email_reg"];
			$name = SafeFormValue('name_reg');
			$address = SafeFormValue('address_reg');
			$phone = SafeFormValue('phone_reg');
			$birthday_reg = $_POST["year"] .'-'. $_POST["month"] .'-'. $_POST["day"];
			
			$arr = array();
			$arr['name'] = $name;	
			$arr['address'] = $address;
			$arr['phone'] = $phone;
			$arr['birthday'] = $birthday_reg;
			
			vaUpdate('member',$arr, "id='" . $_SESSION['member_id'] . "'");	
			
			$_SESSION['mess'] = MODIFY_SUCCESSFULLY;
			
			$_SESSION['member_name'] = $name;
			$_SESSION['member_address'] = $address;
			$_SESSION['member_phone'] = $phone;
			
			include("./includes/mail_config.php");
			global $mail;
			$mailTemplatePath = './EmailTemplate/ModifyMember' .'_' . $_SESSION['lg'] . '.html';
			
			$fh = fopen($mailTemplatePath, 'r');
				
			$template = fread($fh, filesize($mailTemplatePath));
			
			fclose($fh);
			
			$template = str_replace('[NAME]', $name, $template);
			$template = str_replace('[ADDRESS]', $address, $template);
			$template = str_replace('[PHONE]', $phone, $template);
			$template = str_replace('[BIRTHDAY]', $birthday_reg, $template);
			
			$mail_subject = MODIFY_INFORMATION;
			$mail_content = $template;
			$mail_to = $email;
			//$mail_bcc = CST_ADMIN_EMAIL;
			
			$mail->Subject = $mail_subject;
		
			$mail->MsgHTML($mail_content);
		
			$mail->AddAddress($mail_to, "Webmaster");
			//$mail->AddBCC($mail_bcc, "Webmaster");
		
			$mail->Send();	
		}
		else{
			$_SESSION['mess'] = CaptchaWrong;		
		}
		
		page_transfer2($FullUrl . $prefix_url . 'member-detail.html');
	}
}

function Detail()
{
	global $db, $mem_detail;
	
	if(isset($_SESSION['member_id']))
	{
		$sql = "select id, email, phone, name, address, DAY(birthday) as day, MONTH(birthday) as month, YEAR(birthday) as year from member where id = " . $_SESSION['member_id'];	
		$mem_detail = $db->getRow($sql);
	}
}

function ResetPass()
{
	global $db,$act, $msg, $new_pass, $mail, $FullUrl, $prefix_url;
	$code = SafeQueryString("code");
	$page = 'reset-password.html';
	
	if(!empty($code))
	{
		$sql = "select code_time, id_member from confirmation where confirmation_code = '$code' and enable = '0'";
		
		$r = $db->getRow($sql);
	
		$now = getdate();
		$f_date = $r['code_time'];
		
		if(MinExpiresCodeTime($now, $f_date, '30')){
			if($r){
				$id_member = $r['id_member'];						
					
				$new_pass = GenRandomString();
				
				$sql = "select email, name, id, address, phone from member where id='" . $id_member . "'";
				$r = $db->getRow($sql);
				
				$link = 'http://www.' . GetFullDomain() . $FullUrl . "/" . "change-password.html";
				
				if(SendEmailResetPasswordSuccessfull($link, $new_pass, $r['email'], './EmailTemplate/ResetPasswordSuccessfully_'.$_SESSION['lg'].'.html', RESET_PASSWORD_SUCCESSFULLY_SUBJECT)){
				$_SESSION['member_login'] = 1;
				$_SESSION['member_id'] = $r['id'];
				$_SESSION['member_email'] = $r['email'];
				$_SESSION['member_name'] = $r['name'];
				$_SESSION['member_password'] = md5($new_pass);
				$_SESSION['member_address'] = $r['address'];
				$_SESSION['member_phone'] = $r['phone'];
					
				$arr = array();
				$arr['password'] = md5($new_pass);	
				
				vaUpdate('member',$arr, "id='" . $id_member . "'");	
					
				$arr = array();
				$arr['enable'] = 1;			
				
				vaUpdate('confirmation',$arr, "id_member = '" . $id_member . "'");
				$_SESSION['mess'] = RESET_PASSWORD_SUCCESSFULLY;
				
				$page = 'change-password.html';
				}
				else
					$page = 'index.html';
			}
		}
		else{
			$_SESSION['mess'] = OUT_OF_DATE_LINK;
			$page = 'forgot-password.html';
		}
	}
	
	page_transfer2($FullUrl . $prefix_url . $page);
}

function SendEmailResetPasswordSuccessfull($link, $password, $email, $template_path, $subject){
	include("./includes/mail_config.php");
	global $mail;
	$fh = fopen($template_path, 'r');
		
	$template = fread($fh, filesize($template_path));
	
	fclose($fh);
	
	$template = str_replace('[LINK]', $link, $template);
	$template = str_replace('[PASSWORD]', $password, $template);
	
	$mail_subject = $subject;
	$mail_content = $template;
	$mail_to = $email;
	
	$mail->Subject = $mail_subject;

	$mail->MsgHTML($mail_content);

	$mail->AddAddress($mail_to, "Webmaster");
	
	if(!$mail->Send()) {
		$_SESSION['mess'] = SEND_EMAIL_RESET_PASSWORD_UNSUCCESSFULLY_MESS;
		return false;
	} else {
		return true;
	}
}

function MinExpiresCodeTime($now, $code_time, $min)
{
	$now = getdate();
	
	$s_value = $code_time;
			
	$e_value = $s_value + ('60' * $min);
	
	$m_value = valueDate($now);
	
	if($m_value >= $s_value && $m_value <= $e_value)
	{
		return 1;
	}	
	else 
	{
		return 0;
	} 
}

function MinExpires($now, $firtMin, $min)
{
	$now = getdate();
	$s_value = ValueDate($firtMin);
	
	$e_value = ValueDateAddMin($firtMin, $min);
	
	$m_value = valueDate($now);
	
	if($m_value >= $s_value && $m_value <= $e_value)
	{
		return 1;
	}	
	else 
	{
		return 0;
	} 
}

function ValueDate($date_value)
{
	return 	$date_value['0'];
}

function ValueDateAddMin($date_value, $min)
{
	$temp = valueDate($date_value);
	$temp2 = (int)('60' * $min);
	
	return 	 $temp + $temp2;
}

function ForgotPass($tbResetPassword)
{
	global $db,$act, $msg, $mail, $FullUrl, $prefix_url, $lg;
	$email = isset($_POST["email_forgot"]) ? $_POST["email_forgot"] : "";		
	$page = 'forgot-password.html';
	
	if(CorrectGoogleCaptcha())
	{
		if(!empty($email) && IsValidEmail($email))
		{
			$sql = "select email, id, password from ".$tbResetPassword." where email='" . $email . "'";
			$r = $db->getRow($sql);
			
			$page = 'forgot-password.html';
			if($r){
				$confirmation_code = md5($r['email'] . $r['password'] . time());
				$id_member = $r['id'];
				
				$arr = array();
				$arr['confirmation_code'] = $confirmation_code;
				$arr['id_member'] = $id_member;
				
				$now = getdate();
				$arr['code_time'] = $now['0'];
				
				vaInsert('confirmation',$arr);
				
				$link = 'http://www.' . GetFullDomain() . $FullUrl . "/" . "index.php?do=member&act=resetpass&code=" . $confirmation_code . "&lg=" . $lg;
				
				if(SendEmailForgotPassword($link, $r['email'], './EmailTemplate/ForgotPassword_'.$_SESSION['lg'].'.html', RESET_PASSWORD_SUBJECT))
				{
					$_SESSION['mess'] = FORGOT_PASSWORD_MESS;	
				}
				else
					$page = 'index.html';
			}
		}
	}
	else{			
		$_SESSION['mess'] =  WRONG_CAPTCHA_CODE_MESS;
	}
	
	page_transfer2($FullUrl . $prefix_url . $page);
}

function SendEmailForgotPassword($link, $email, $template_path, $subject){
	include("./includes/mail_config.php");
	global $mail;
	$fh = fopen($template_path, 'r');
		
	$template = fread($fh, filesize($template_path));
	
	fclose($fh);
	
	$template = str_replace('[LINK]', $link, $template);
	
	$mail_subject = $subject;
	$mail_content = $template;
	$mail_to = $email;
	
	$mail->Subject = $mail_subject;

	$mail->MsgHTML($mail_content);

	$mail->AddAddress($mail_to, "Webmaster");

	if(!$mail->Send()) {
		$_SESSION['mess'] = SEND_EMAIL_RESET_PASSWORD_UNSUCCESSFULLY_MESS;
		return false;
	} else {
		return true;
	}
}

function Vote(){
	global $db, $FullUrl, $prefix_url;
	
	$vote = SafeQueryString('vote');
	$art_id = SafeQueryString('art_id');
	$pro_id = SafeQueryString('pro_id');
	$page = trim(isset($_GET['link'])?$_GET['link']:$FullUrl. '/index.php');
	
	if(!empty($art_id) && is_numeric($art_id) && is_numeric($vote))
	{
		if(!AlreadyVoteArticle($art_id))
		{
			$arr = array();
			$arr['vote'] = $vote;
			$arr['vote_article_id'] = $art_id;
			vaInsert('votes',$arr);
			
			$sql = "select vote from votes where vote_article_id=" . $art_id;
			$votes = $db->getAll($sql);
			if($votes){
				$arr2 = array();
				
				$mark = 0;
				foreach($votes as $vote)
					$mark += $vote['vote'];
				$arr2['vote'] = floor($mark/count($votes) + 0.5);
				
				vaUpdate("articles", $arr2, " id=" . $art_id);
				
				$_SESSION['mess'] = VOTE_SUCCESSFULLY_MESS;
			}
		}
		else
		{
			$_SESSION['mess'] = ALREADY_VOTE_MESS;
		}
	}
	else if(!empty($pro_id) && is_numeric($pro_id)  && is_numeric($vote))
	{
		if(!AlreadyVoteProduct($pro_id))
		{
			$arr = array();
			$arr['vote'] = $vote;
			$arr['vote_pro_id'] = $pro_id;
			vaInsert('votes',$arr);
			
			$sql = "select vote from votes where vote_pro_id = " . $pro_id;
			$votes = $db->getAll($sql);
			if($votes){
				$arr2 = array();
				
				$mark = 0;
				foreach($votes as $vote)
					$mark += $vote['vote'];
				$arr2['vote'] = floor($mark/count($votes) + 0.5);
				
				vaUpdate("products", $arr2, " id=" . $pro_id);
				
				$_SESSION['mess'] = VOTE_SUCCESSFULLY_MESS;
			}	
		}
		else
		{
			$_SESSION['mess'] = ALREADY_VOTE_MESS;
		}
	}
	
	page_transfer2($FullUrl . $page);
}

function AlreadyVoteArticle($ArticleId){
	$UniqueSession = "ArticlesAreVoted";
	$ArticleIdString = "[" . $ArticleId . "]";
	
	if(!isset($_SESSION[$UniqueSession]))
	{
		$_SESSION[$UniqueSession] = $ArticleIdString;
	}
	else
	{
		$mystring = $_SESSION[$UniqueSession];
		$findme = $ArticleIdString;
		$pos = strpos($mystring, $findme);
		
		if($pos === false)
		{
			$_SESSION[$UniqueSession] .= $ArticleIdString;
		}
		else
			return true;
	}
	
	return false;
}

function AlreadyVoteProduct($ProductId){
	$UniqueSession = "ProductsAreVoted";
	$ProductIdString = "[" . $ProductId . "]";
	
	if(!isset($_SESSION[$UniqueSession]))
	{
		$_SESSION[$UniqueSession] = $ProductIdString;
	}
	else
	{
		$mystring = $_SESSION[$UniqueSession];
		$findme = $ProductIdString;
		$pos = strpos($mystring, $findme);
		
		if($pos === false)
		{
			$_SESSION[$UniqueSession] .= $ProductIdString;
		}
		else
			return true;
	}
	
	return false;
}

function AddToFav(){
	global $db, $FullUrl, $prefix_url;
	
	$art_id = SafeQueryString('art_id');
	$pro_id = SafeQueryString('pro_id');
	$page = trim(isset($_GET['link'])?$_GET['link']:$FullUrl . $prefix_url . 'index.php');
	
	if(!empty($art_id) && is_numeric($art_id) && isset($_SESSION['member_id']))
	{
		$mem_id =  $_SESSION['member_id'];
		$sql = "select fav_article_id from favourite where fav_article_id = $art_id and fav_mem_id = $mem_id";
		$r = $db->getRow($sql);
		
		if($r)
		{
			$_SESSION['mess'] = EXIST_FAVOURITE_MESS;
		}
		else
		{
			$arr['fav_article_id'] = $art_id;
			$arr['fav_mem_id'] = $mem_id;
			
			vaInsert('favourite',$arr);
			$_SESSION['mess'] = ADD_TO_FAVOURITE_SUCCESSFULLY;
		}
	}
	else if(!empty($pro_id) && is_numeric($pro_id) && isset($_SESSION['member_id']))
	{
		$mem_id = $_SESSION['member_id'];
		$sql = "select fav_pro_id from favourite where fav_pro_id = $pro_id and fav_mem_id = $mem_id";
		$r = $db->getRow($sql);
		
		if($r)
		{
			$_SESSION['mess'] = EXIST_FAVOURITE_MESS;
		}
		else
		{
			$arr['fav_pro_id'] = $pro_id;
			$arr['fav_mem_id'] = $mem_id;
			
			vaInsert('favourite',$arr);
			$_SESSION['mess'] = ADD_TO_FAVOURITE_SUCCESSFULLY;
		}
	}
	
	page_transfer2($page);
}

function DelToFav(){
	global $db, $FullUrl, $prefix_url;
	
	$art_id = SafeQueryString('art_id');
	$pro_id = SafeQueryString('pro_id');
	$page = trim(isset($_GET['link'])?$_GET['link']:$FullUrl . $prefix_url . 'index.php');
	
	if(!empty($art_id) && is_numeric($art_id) && isset($_SESSION['member_id']))
	{
		$mem_id =  $_SESSION['member_id'];
		$sql = "select fav_id from favourite where fav_article_id = $art_id and fav_mem_id = $mem_id";
		
		$r = $db->getRow($sql);
		
		if($r)
		{
			$fav_id = $r['fav_id'];
			
			vaDelete('favourite','fav_id =' . $fav_id);
			$_SESSION['mess'] = DEL_TO_FAVOURITE_SUCCESSFULLY;
			
		}
		else
		{
			$_SESSION['mess'] = NO_EXIST_FAVOURITE_MESS;
		}
	}
	else if(!empty($pro_id) && is_numeric($pro_id) && isset($_SESSION['member_id']))
	{
		$mem_id = $_SESSION['member_id'];
		$sql = "select fav_id from favourite where fav_pro_id = $pro_id and fav_mem_id = $mem_id";
		
		$r = $db->getRow($sql);
		
		if($r)
		{
			$fav_id = $r['fav_id'];
			
			vaDelete('favourite','fav_id =' . $fav_id);
			$_SESSION['mess'] = DEL_TO_FAVOURITE_SUCCESSFULLY;
		}
		else
		{
			$_SESSION['mess'] = EXIST_FAVOURITE_MESS;
		}
	}
	
	page_transfer2($page);
}

function Comment()
{
	global $db, $FullUrl, $prefix_url;
	
	$email = SafeFormValue('email');
	$password = md5(SafeFormValue('password'));
	$comment = SafeFormValue('content');
	$security_code = trim(isset($_POST['security_code'])?$_POST['security_code']:'');
	$art_id = SafeQueryString('art_id');
	$pro_id = SafeQueryString('pro_id');
	$page = trim(isset($_POST['previous_url'])?($FullUrl.$_POST['previous_url']):($FullUrl. $prefix_url. '/index.php'));
	
	if(!empty($comment) && is_numeric($art_id))
	{
		if((isset($_SESSION['security_code'])) && ($security_code == $_SESSION['security_code']))
		{
			if(!isset($_SESSION['member_id']))
			{
				if(!empty($email) && IsValidEmail($email) && !empty($password) && !empty($comment) && is_numeric($art_id))
				{
					$sql = "select id, email, password, name from member where email = '$email' and password = '$password'";
					$r = $db->getRow($sql);
					
					if($r)
					{
						$_SESSION['member_login'] = 1;
						$_SESSION['member_password'] = $r['password'];
						$_SESSION['member_email'] = $r['email'];
						$_SESSION['member_name'] = $r['name'];
						$_SESSION['member_id'] = $r['id'];
		   
						$arr['cmt_mem_id'] = $r['id'];
						$arr['cmt_article_id'] = $art_id;
						$arr['cmt_content'] = strip_tags($comment);
						$arr['cmt_active'] = 1;
						
						vaInsert('comments',$arr);
						$_SESSION['mess'] = COMMENT_SUCCESSFULLY_MESS;
						
						unset($_SESSION['security_code']);
					}
					else
					{
						$_SESSION['mess'] = FAIL_LOGIN_MESS;	
					}
				}
				
			}
			else
			{
				$arr['cmt_mem_id'] = $_SESSION['member_id'];
				$arr['cmt_article_id'] = $art_id;
				$arr['cmt_content'] = $comment;
				$arr['cmt_active'] = 1;
				
				vaInsert('comments',$arr);
				$_SESSION['mess'] = COMMENT_SUCCESSFULLY_MESS;
				
				unset($_SESSION['security_code']);
				//echo $page;
			}
		}
		else
		{
			$_SESSION['mess'] = WRONG_CAPTCHA_CODE_MESS;
			$_SESSION['comment_email'] = $email;
			$_SESSION['comment_content'] = $comment;
		}
		
	}
	else if(!empty($comment) && is_numeric($pro_id))
	{
		if((isset($_SESSION['security_code'])) && ($security_code == $_SESSION['security_code']))
		{
			if(!isset($_SESSION['member_id']))
			{
				if(!empty($email) && IsValidEmail($email) && !empty($password) && !empty($comment) && is_numeric($pro_id))
				{
					$sql = "select id, email, password, name from member where email = '$email' and password = '$password'";
					$r = $db->getRow($sql);
					
					if($r)
					{
						$_SESSION['member_login'] = 1;
						$_SESSION['member_password'] = $r['password'];
						$_SESSION['member_email'] = $r['email'];
						$_SESSION['member_name'] = $r['name'];
						$_SESSION['member_id'] = $r['id'];
		   
						$arr['cmt_mem_id'] = $r['id'];
						$arr['cmt_pro_id'] = $pro_id;
						$arr['cmt_content'] = strip_tags($comment);
						
						vaInsert('comments',$arr);
						$_SESSION['mess'] = COMMENT_SUCCESSFULLY_MESS;
						
						unset($_SESSION['security_code']);
					}
					else
					{
						$_SESSION['mess'] = FAIL_LOGIN_MESS;	
					}
				}
			}
			else
			{
				$arr['cmt_mem_id'] = $_SESSION['member_id'];
				$arr['cmt_pro_id'] = $pro_id;
				$arr['cmt_content'] = $comment;
				
				vaInsert('comments',$arr);
				$_SESSION['mess'] = COMMENT_SUCCESSFULLY_MESS;
				
				unset($_SESSION['security_code']);
			}
		}
		else
		{
			$_SESSION['mess'] = WRONG_CAPTCHA_CODE_MESS;
			$_SESSION['comment_email'] = $email;
			$_SESSION['comment_content'] = $comment;
		}
	}
	//echo $page;
	page_transfer2($page);
}

function Register($tbRegister)
{
	global $db, $FullUrl, $prefix_url;
	$email_reg = CleanSQLInjection(trim(isset($_POST["email_reg"])?$_POST["email_reg"] : ''));
	$password_reg = CleanSQLInjection(isset($_POST["password_reg"])?$_POST["password_reg"] : '');
	$name_reg = CleanSQLInjection(trim(isset($_POST["name_reg"])?$_POST["name_reg"] : ''));
	$address_reg = CleanSQLInjection(trim(isset($_POST["address_reg"])?$_POST["address_reg"] : ''));
	$phone_reg = CleanSQLInjection(trim(isset($_POST["phone_reg"])?$_POST["phone_reg"] : ''));
	$birthday_reg = $_POST["year"] .'-'. $_POST["month"] .'-'. $_POST["day"];
	if(isset($_GET['page']) && $_GET['page'] == 'checkout')
	{
		$page = "index.php?do=cart&act=checkout&lg=" . $_SESSION['lg'];
	}
	else
		$page = "register.html";
	
	
	if(CorrectGoogleCaptcha())
	{
		if(!empty($password_reg)  && !empty($name_reg) && IsValidEmail($email_reg))
		{
			$sql = "select email from ". $tbRegister ." where email='" . $email_reg . "'";
			$r = $db->getRow($sql);
			
			if($r)
			{
				$_SESSION['form_name'] = $name_reg;
				$_SESSION['form_email'] = $email_reg;
				$_SESSION['form_phone'] = $phone_reg;
				$_SESSION['form_address'] = $address_reg;
				$_SESSION['form_year'] = $_POST["year"];
				$_SESSION['form_month'] = $_POST["month"];
				$_SESSION['form_day'] = $_POST["day"];
				
				$_SESSION['mess'] = EMAIL_EXIST_MESS;
			}
			else
			{
				$arr['password'] = md5($password_reg);
				$arr['email'] = $email_reg;
				$arr['name'] = $name_reg;	
				$arr['address'] = $address_reg;
				$arr['phone'] = $phone_reg;
				$arr['birthday'] = $birthday_reg;
				$arr['group']= 1;	
				
				$member_id = vaInsert($tbRegister,$arr);
				
				$_SESSION['member_login'] = 1;
				$_SESSION['member_id'] = $member_id;
				$_SESSION['member_email'] = $email_reg;
				$_SESSION['member_name'] = $name_reg;
				$_SESSION['member_address'] = $address_reg;
				$_SESSION['member_phone'] = $phone_reg;
				$_SESSION['member_password'] = md5($password_reg);
				$_SESSION['member_group'] = $arr['group'];
				
				$_SESSION['mess'] = SIGN_UP_SUCCESSFULLY;
				SendEmailConfirmRegistration($name_reg, $email_reg);
				
				if(isset($_GET['page']) && $_GET['page'] == 'checkout')
				{
					$page = "index.php?do=cart&act=checkout&lg=" . $_SESSION['lg'];
				}
				else
					$page = "index.php";
			}
		}
	}
	else
	{
		$_SESSION['form_name'] = $name_reg;
		$_SESSION['form_email'] = $email_reg;
		$_SESSION['form_phone'] = $phone_reg;
		$_SESSION['form_address'] = $address_reg;
		$_SESSION['form_year'] = $_POST["year"];
		$_SESSION['form_month'] = $_POST["month"];
		$_SESSION['form_day'] = $_POST["day"];
		
		$_SESSION['mess'] = CaptchaWrong;
	}
	
	page_transfer2($FullUrl . $prefix_url . $page);
}

function SendEmailConfirmRegistration($name, $email){
	include("./includes/mail_config.php");
	global $mail;
	$mailTemplatePath = './EmailTemplate/ConfirmRegistration' .'_' . $_SESSION['lg'] . '.html';
	
	$fh = fopen($mailTemplatePath, 'r');
		
	$template = fread($fh, filesize($mailTemplatePath));
	
	fclose($fh);
	
	$template = str_replace('[NAME]', $name, $template);
	
	$mail_subject = EMAIL_REGISTRATION_CONFIRM_SUBJECT;
	$mail_content = $template;
	$mail_to = $email;
	//$mail_bcc = CST_ADMIN_EMAIL;
	
	$mail->Subject = $mail_subject;

	$mail->MsgHTML($mail_content);

	$mail->AddAddress($mail_to, "Webmaster");
	//$mail->AddBCC($mail_bcc, "Webmaster");

	$mail->Send();	
}

function ChangePass($tbChangePassword)
{
	global $db,$act, $msg, $FullUrl, $prefix_url;
	
	$page = "change-password.html";

	if(isset($_SESSION["member_email"]))
	{
		$email_change = $_SESSION["member_email"];
		$sql = "select password from ". $tbChangePassword ." where email='" . $email_change . "'";
		$r = $db->getRow($sql);
		
		if($r){
			$PasswordOld = md5(SafeFormValue("password_old"));
			$PasswordNew = md5(SafeFormValue("password_new"));
			
			if(!empty($PasswordOld) && !empty($PasswordNew)){
				
				if($PasswordOld == $r['password']){
					$arr = array();
					$arr['password'] = $PasswordNew;
					vaUpdate($tbChangePassword,$arr, "email = '" .  $email_change . "'");
					
					$_SESSION['member_password'] = $PasswordNew;
					$_SESSION['mess'] = CHANGE_PASSWORD_SUCCESSFULL;
					$page = "index.html";
				}
				else
				{
					$_SESSION['mess'] = PASSWORD_OLD_INCORRECT;
				}
			}
		}
	}
	
	page_transfer2($FullUrl . $prefix_url . $page);
}

function EmailPasswordExists($email, $password, $tbEmail)
{
	global $db, $msg;
	
	$sql = "select email, password, name, address, phone, id from ". $tbEmail ." where email='" . $email . "'";
	$r = $db->getRow($sql);
	$msg=4;
	
	if($r){
		if($r['password'] == md5($_POST['password'])){
			$_SESSION['member_password'] = $r['password'];
			$_SESSION['member_email'] = $r['email'];
			$_SESSION['member_name'] = $r['name'];
			$_SESSION['member_address'] = $r['address'];
			$_SESSION['member_phone'] = $r['phone'];
			$_SESSION['member_id'] = $r['id'];
			$_SESSION['member_login'] = 1;
			
			return true;
		}
	}
	
	else
	{
		$_SESSION['counter_login']++;
		$msg = UserPasswordError;		
		return false;
	}
}
function Login()
{
	global $db, $msg, $FullUrl, $prefix_url, $page;
	
	$email = CleanSQLInjection(trim(isset($_POST['email']) ? $_POST['email'] : ''));
	$password = CleanSQLInjection(trim(isset($_POST['password']) ? $_POST['password'] : ''));
	$tbEmail = "member";
	
	if(!isset($_SESSION['counter_login'])){
		$_SESSION['counter_login'] = 0;
	}
	
	if($_SESSION['counter_login'] > 1)
	{
		if(isset($_POST['security_code']) && $_POST['security_code'] == $_SESSION['security_code']){
			
			if(EmailPasswordExists($email, $password, $tbEmail))
			{
				// Successfull
				$msg= SuccessfullLogin;
				if(isset($_GET['page']) && $_GET['page'] == 'checkout')
				{
					$page = "index.php?do=cart&act=checkout&lg=" . $_SESSION['lg'];
				}
				else
					$page = "index.php";
				page_transfer($msg, $FullUrl . $prefix_url . $page);
			}
			else
			{
				// Fail
				$_SESSION['counter_login']++;
				$msg = UserPasswordError;
				if(isset($_GET['page']) && $_GET['page'] == 'checkout')
				{
					$page = "index.php?do=cart&act=checkout&lg=" . $_SESSION['lg'];
				}
				else if(isset($_GET['page']) && $_GET['page'] == 'checkout')
				{
					$page = "index.php?do=cart&act=checkout&lg=" . $_SESSION['lg'];
				}
				else
					$page = "index.php";
				page_transfer($msg, $FullUrl . $prefix_url . $page);				
			}
		}
		else
		{
			// Fail
			$_SESSION['counter_login']++;
			$msg = WRONG_CAPTCHA_CODE_MESS;
			if(isset($_GET['page']) && $_GET['page'] == 'checkout')
			{
				$page = "index.php?do=cart&act=checkout&lg=" . $_SESSION['lg'];
			}
			else
				$page = "index.php";
			page_transfer($msg, $FullUrl . $prefix_url . $page);				
		}
	}
	else
	{
		if(EmailPasswordExists($email, $password, $tbEmail))
		{
			// Successfull
			$msg= SuccessfullLogin;
			if(isset($_GET['page']) && $_GET['page'] == 'checkout')
			{
				$page = "index.php?do=cart&act=checkout&lg=" . $_SESSION['lg'];
			}
			else
				$page = "index.php";
			page_transfer($msg,$FullUrl . $prefix_url . $page);
		}
		else
		{
			// Fail
			$_SESSION['counter_login']++;
			$msg = UserPasswordError;
			if(isset($_GET['page']) && $_GET['page'] == 'checkout')
			{
				$page = "index.php?do=cart&act=checkout&lg=" . $_SESSION['lg'];
			}
			else
				$page = "index.php";
			page_transfer($msg,$FullUrl . $prefix_url . $page);				
		}
	}
}

function Logout()
{
	global $msg, $FullUrl, $prefix_url;
	
	if(isset($_SESSION['member_login']))
		unset($_SESSION['member_login']);
	
	if(isset($_SESSION['member_email']))
		unset($_SESSION['member_email']);
		
	if(isset($_SESSION['member_password']))
		unset($_SESSION['member_password']);
		
	if(isset($_SESSION['member_name']))
		unset($_SESSION['member_name']);
		
	if(isset($_SESSION['member_address']))
		unset($_SESSION['member_address']);
		
	if(isset($_SESSION['member_phone']))
		unset($_SESSION['member_phone']);	
	
	if(isset($_SESSION['member_id']))
		unset($_SESSION['member_id']);
	
	if(isset($_SESSION['counter_login']))
		unset($_SESSION['counter_login']);
		
	$msg = LogoutFinish;
	$page = "index.php";
	page_transfer($msg, $FullUrl . $prefix_url . $page);
}

function ShowContact()
{
	global $db, $contact, $email;
	$sql = 'select * from info where name_vn=\'contact\'';    
    $contact = $db->getRow($sql);
	$sql = 'select * from info where name_vn=\'email\'';    
    $email = $db->getRow($sql);
}

?>